import {XGXX1, XGXX2, ADDCART, ADDCOUNTER, ADDTOCART, SIGNIN, REFIST, ADDUSER, ADDUSERINFO} from './mutaions-types'
export default {
  // context 上下文  ==> store
  [XGXX2](context, payload) {
    console.log(payload.message)
    payload.sucess()
    setTimeout(() => {
      context.commit({
        type: XGXX1
      })
    }, 1000);
  },
  // 添加购物车
  [ADDCART](context, payload) {
    return new Promise((resolve,reject) => {
      // payload 新添加的商品
      // let oldProduct = null

      // for (let item of state.cartList) {
      //   if (item.iid === payload.iid) {
      //     oldProduct = item
      //   }
      // }

      let oldProduct = context.state.cartList.find(item => item.iid === payload.iid)

      // 判断购物车是否已经有 该商品了 如果已经有 则 该商品的数量加一 否则 添加该商品  

      if (oldProduct) { // 商品数量加一
        context.commit(ADDCOUNTER, oldProduct)
        resolve('当前商品数量 +1')
      }else { // 添加新的商品
        payload.count = 1
        payload.checked = true
        context.commit(ADDTOCART, payload)
        resolve('添加购物车成功')
      }
    })

  },
  // 登录验证
  [SIGNIN](context, payload) {
    return new Promise((resolve, reject) => {
      const resObj = {
        // 默认 账号不存在
        code: 202,
        message: '账号不存在'
      }

      const itemUser = context.state.users.filter(item => item.user === payload.user)

      // 判断账号是否存在
      if (itemUser.length) {
        // 201 账号存在 
        resObj.code = 201
        resObj.message = '密码错误'

        // 判断密码是否正确
        const item = itemUser[0]
        if (item.psw === payload.psw) {
          resObj.code = 200
          resObj.message = '登录成功'
          
          // 记录登录信息
          window.sessionStorage.setItem('userName', payload.user)
          
          // 添加账号信息 userInfo
          const userInfo = {}
          userInfo.img = 'assets/img/login/buddha.svg'
          userInfo.userName = payload.user
          userInfo.phone = '16673418888'

          context.commit(ADDUSERINFO, userInfo)
        }
      }

      resolve(resObj)

    })
  },
  [REFIST](context, payload) {
    return new Promise((resolve, reject) => {
      const registRes = {
        // 默认注册成功
        code: 200,
        message: '注册成功'
      }

      // 判断注册账号是否已存在
      const flag = context.state.users.filter(item => item.user === payload.user).length

      if (flag) {
        // 账号已存在
        registRes.code = 201 
        registRes.message = '账号已存在'
      }else {
        // 添加账号 payload
        context.commit(ADDUSER, payload)
      }

      resolve(registRes)

    })

  }
}